package org.ailuoli.guard.domain.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.ailuoli.guard.domain.entity.Account;
import org.ailuoli.guard.infrastructure.repository.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tools.bedrock.util.BaseUtils;
import org.tools.encrypt.asymmetric.rsa.RsaHelper;
import org.tools.encrypt.entity.Encrypt;
import org.tools.encrypt.entity.KeyPair;
import org.tools.encrypt.entity.asymmetric.Rsa;

import java.util.List;

/**
 * @author sander
 * @date 2025/01/27
 **/
@Slf4j
@Service
public class AccountService extends ServiceImpl<AccountMapper, Account> {

    @Autowired
    private Encrypt encrypt;

    @Transactional(rollbackFor = Exception.class)
    public boolean saveAccount(Account account) throws Exception {
        if (BaseUtils.isNotEmpty(account.getPassword())) {
            account.setPassword(encode(account.getPassword()));
        }
        return this.save(account);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateAccount(Account account) throws Exception {
        if (BaseUtils.isNotEmpty(account.getPassword())) {
            account.setPassword(encode(account.getPassword()));
        }
        return this.saveOrUpdate(account);
    }

    private String encode(String password) throws Exception {
        return encode(password, null);
    }

    private String encode(String password, String group) throws Exception {
        Rsa rsa = encrypt.getAsymmetric().getRsa();
        if (BaseUtils.isEmpty(rsa)) {
            throw new Exception("Rsa is null");
        }
        if (!rsa.getEnabled()) {
            throw new Exception("Rsa is disabled");
        }
        if (BaseUtils.isNotEmpty(group)) {
            List<KeyPair> rsaGroup = rsa.getGroup();
            if (BaseUtils.isEmpty(rsaGroup)) {
                log.error("Rsa group is null");
            }
            for (KeyPair keyPair : rsaGroup) {
                if (group.equals(keyPair.getName())) {
                    RsaHelper.load(keyPair);
                    return RsaHelper.encode(password);
                }
            }
        }
        RsaHelper.load(rsa);
        return RsaHelper.encode(password);
    }

}
